<?php

namespace app\admin\controller;

use app\admin\dict\IconDict;
use app\admin\model\Admin;
use app\admin\model\AdminLog;
use app\admin\model\AuthRule;
use app\common\controller\BaseAdminController;
use think\facade\Event;

class Index extends BaseAdminController
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['login'];
    protected $menus_array = [];
    public function _initialize()
    {
        parent::_initialize();
        $menus_array = AuthRule::getAllMenuArray(config('app.app_debug')==1?true:false);
        $this->menus_array = $menus_array;
    }
    /**
     * 首页
     * @return \think\response\Json
     */
    public function index()
    {
//        $res = AuthRule::getAllMenuStr(config('app.app_debug')==1?true:false);
//        $this->view->assign('menus', $res);
//        $this->assignconfig('menus_array', $menus_array);
        $this->assignconfig('userinfo', $this->auth->getUserinfo());
        return $this->view->fetch();
    }

    /**
     * 登录页
     * @return mixed
     */
    public function login()
    {
        if($this->request->isAjax()){
            $data = $this->request->param('row/a');
            $res = $this->auth->login($data['username'], $data['password']);
            AdminLog::setTitle(__('Login'));
            if($res){
                Event::trigger('admin_login_after', $this->request);
                $this->success(__('Login successful'), 'index',
                    ['url' => 'index', 'id' => $this->auth->id, 'username' => $data['username'], 'avatar' => $this->auth->avatar]);
            }else{
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, '');
            }
        }
        return $this->view->fetch();
    }

    /**
     * 获取用户信息
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_user_info()
    {
        $user = Admin::where('id',$this->auth->id)->withoutField('password')->find();
        return $this->success("获取成功",'',$user);
    }

    /**
     * 获取菜单
     * @return mixed
     * @throws \Exception
     */
    public function get_menu()
    {
        return $this->success("获取成功",'',$this->menus_array);
    }
    /**
     * 注销登录.
     */
    public function logout()
    {
        $this->auth->logout();
        Event::trigger('admin_logout_after', $this->request);
        $this->success(__('Logout successful'), 'index/login',['url'=>'index/login']);
    }
//    public function test()
//    {
//        return $this->view->fetch();
//    }

    /**
     * 获取图标
     * @return mixed
     */
    public function get_icon()
    {
        return $this->view->fetch();
    }
}